<template>
	<view class="register">
		<u-navbar title="注册" :autoBack="true"
			titleStyle="color:#d1f5f8;margin-left:-73%;margin-top:-0.5%;font-size:30rpx;" leftIconSize="30rpx"
			leftIconColor="#d1f5f8" placeholder bgColor="#01a7f4" height="75rpx" />
		<view class="register_content">
			<h4 style="text-align: center;">欢迎注册</h4>

			<u--form labelPosition="left" :model="registerForm" :rules="rules" ref="formRef"
				labelStyle="font-size:30rpx;">
				<u-form-item prop="headImg" ref="item0">

					<view style="margin: 0 auto;"><u-upload maxCount="1" :fileList="fileList1" name="1"
							@afterRead="afterRead" @delete="deletePic" :previewFullImage="true"
							uploadText="上传头像,可选"></u-upload>
					</view>
				</u-form-item>
				<u-form-item prop="schoolId" ref="item1">
					<text style="margin-left:15rpx"><u-icon name="home" size="35rpx" color="#4f63e7"></u-icon></text>
					<uni-combox :candidates="schools" placeholder="请选择所在学校,必选"
						v-model="registerForm.schoolId"></uni-combox>
				</u-form-item>
				<u-form-item prop="studentId" ref="item2">
					<u--input type="number" v-model="registerForm.studentId" customStyle="height:80rpx;"
						prefixIcon="tags" placeholder="请输入学号,必填" placeholderStyle="color:#4f63e7;font-size:20rpx"
						prefixIconStyle="color:#4f63e7;font-size:40rpx" fontSize="30rpx" shape="circle"></u--input>
				</u-form-item>
				<u-form-item prop="username" ref="item3">
					<u--input v-model="registerForm.username" customStyle="height:80rpx;" prefixIcon="account"
						placeholder="请输入用户名,必填" placeholderStyle="color:#4f63e7;font-size:20rpx"
						prefixIconStyle="color:#4f63e7;font-size:40rpx" fontSize="30rpx" shape="circle"></u--input>
				</u-form-item>
				<u-form-item prop="phone" ref="item4">
					<u--input v-model="registerForm.phone" customStyle="height:80rpx;" prefixIcon="phone"
						placeholder="请输入手机号,必填" placeholderStyle="color:#4f63e7;font-size:20rpx"
						prefixIconStyle="color:#4f63e7;font-size:40rpx" fontSize="30rpx" shape="circle"></u--input>
				</u-form-item>
				<u-form-item prop="password" ref="item5">
					<u--input :type="pwdStatus.type" v-model="registerForm.password" customStyle="height:80rpx;"
						placeholder="请输入密码,必填" prefixIcon="lock" placeholderStyle="color:#4f63e7;font-size:20rpx"
						prefixIconStyle="color:#4f63e7;font-size:40rpx" fontSize="30rpx" shape="circle">
						<template #suffix>
							<up-image :src="pwdStatus.src" width="50rpx" height="50rpx"
								@click="changeStatus"></up-image>
						</template>
					</u--input>
				</u-form-item>
				<u-form-item prop="checkCode" ref="item6">
					<u--input type="number" v-model="registerForm.checkCode" customStyle="height:80rpx;"
						placeholder="请输入验证码,目前尚未开通" prefixIcon="level" placeholderStyle="color:#4f63e7;font-size:20rpx"
						prefixIconStyle="color:#4f63e7;font-size:40rpx" fontSize="30rpx" shape="circle"></u--input>
					<view class="wrap">
						<u-toast ref="uToastRef"></u-toast>
						<u-code :seconds="seconds" @end="end" @start="start" ref="uCode" @change="codeChange"></u-code>
						<u-button @tap="getCode" type="primary">{{tips}}</u-button>
					</view>
				</u-form-item>
				<u-form-item prop="inviteCode" ref="item7">
					<u--input type="text" v-model="registerForm.invitedCode" customStyle="height:80rpx;"
						placeholder="请输入邀请码,选填" prefixIcon="star" placeholderStyle="color:#4f63e7;font-size:20rpx"
						prefixIconStyle="color:#4f63e7;font-size:40rpx" fontSize="30rpx" shape="circle"></u--input>
				</u-form-item>
				<view style="width: 90%;margin: 30rpx auto;display: flex;flex-direction: column;">
					<u-button type="primary" text="点击注册" size="large" @click="toRegister"
						throttleTime="1500"></u-button>
					<view style="display: flex;font-size: 20rpx;align-items: center;margin-bottom:50rpx">
						<u-checkbox :checked="agree" @change="changeAgree"></u-checkbox>
						<text>我已阅读并同意<text style="color: #3c9cff;">《注册协议》</text>及<text
								style="color: #3c9cff;">《隐私协议》</text></text>
					</view>
				</view>

			</u--form>
			<view style="position: absolute;bottom: 20rpx;right: 20rpx;font-size: 25rpx;color: #3c9cff;"
				@click="returnLogin">
				返回登录
			</view>

		</view>
	</view>
	<!-- 登陆失败的提示 -->
	<u-modal :show="registerFailShow" :content="alert" @confirm="closeRegisterFailShow"></u-modal>
</template>

<script setup>
	import {
		useUserStore
	} from "@/stores/userStore.js"
	import {
		useSchoolStore
	} from "@/stores/schoolStore.js"
	import {
		reactive,
		ref,
		getCurrentInstance,
		onMounted
	} from "vue";
	import md5 from "js-md5";
	const userStore = useUserStore();
	const schoolStore = useSchoolStore();
	const pwdStatus = reactive({
		src: "/static/images/hide.png",
		type: "password"
	})

	function changeStatus() {
		if (pwdStatus.type == "password") {
			pwdStatus.type = "text",
				pwdStatus.src = "/static/images/show.png"
		} else {
			pwdStatus.type = "password",
				pwdStatus.src = "/static/images/hide.png"
		}
	}
	//获取学校列表
	const schools = reactive([

	])
	async function getScoolList() {
		await schoolStore.getSchoolList();
		schoolStore.schoolList.forEach(async (p) => {
			schools.push(p['schoolName'])
		})

	}
	onMounted(() => {
		getScoolList()
	})
	//验证规则
	const rules = reactive({
		schoolId: {
			type: 'string',
			required: true,
			message: '请选择学校',
			trigger: ['blur', 'change'],
		},
		photo: {
			type: "Image",
			required: false,
			message: '请选择照片',
			trigger: ['blur', 'change'],
		},
		studentId: [{
				type: 'number',
				required: true,
				message: '请输入学号',
				trigger: ['blur', 'change'],
			},
			{
				pattern: /^[0-9]{6,12}$/,
				// 正则检验前先将值转为字符串
				required: true,
				message: '学号在6-12位之间',
				trigger: ['blur', 'change']
			}

		],
		username: [{
				type: 'string',
				required: true,
				message: '请输入用户名',
				trigger: ['blur', 'change'],
			},
			{
				type: 'string',
				required: true,
				message: '用户名在1-6位之间,且不能含有空格',
				trigger: ['blur', 'change'],
				pattern: /^\S{1,6}$/
			}
		],

		phone: [{
				type: 'number',
				required: true,
				message: '请输入手机号',
				trigger: ['blur', 'change'],
			},
			{
				pattern: /^1[3456789]\d{9}$/,
				// 正则检验前先将值转为字符串
				required: true,
				message: '手机号格式错误',
				trigger: ['blur', 'change']
			}
		],
		password: [{
				type: 'string',
				required: true,
				message: '请输入密码',
				trigger: ['blur', 'change'],
			},
			{
				type: 'string',
				required: true,
				message: '密码在6-12位之间，且不含有空格',
				trigger: ['blur', 'change'],
				pattern: /^\S{6,12}$/
			}
		],
		checkCode: {
			type: 'number',
			required: false,
			len: 4,
			message: '请填写4位验证码',
			trigger: ['blur', 'change']
		},
		invitedCode: {
			type: 'string',
			required: false
		}

	})

	let registerForm = reactive({
		schoolId: '',
		studentId: '',
		username: '',
		phone: '',
		password: '',
		checkCode: '',
		invitedCode: ''
	})
	const formRef = ref()
	let agree = ref(true)
	const registerFailShow = ref(false);

	function closeRegisterFailShow() {
		registerFailShow.value = false
	}
	const alert = ref("")

	function toRegister() {

		if (agree.value == false) {
			uni.showToast({
				title: "请同意下方条款",
				mask: true,
				duration: 500
			})
		} else {
			formRef.value.validate().then(async res => {
				//表单验证通过
				//模拟登录成功
				schoolStore.schoolList.forEach((p) => {
					if (p.schoolName == registerForm.schoolId) {
						registerForm.schoolId = p.schoolId;
						return;
					}
				})
				registerForm.password = md5(registerForm.password)
				await userStore.register(fileList1.value[0].url, registerForm);
				if (userStore.status.code == "200") {
					uni.setStorageSync("user", JSON.stringify(userStore.user))
					uni.switchTab({
						url: "/pages/user/user"
					})
				} else {
					registerForm.schoolId = ''
					registerFailShow.value = true
					alert.value = userStore.status.msg
				}

			}).catch(errors => {
				//表单验证失败

			})
		}

	}

	function returnLogin() {
		uni.navigateTo({
			url: "/pages/login/login"
		})
	}

	function changeAgree() {
		agree.value = !agree.value
	}
	//照片上传

	const fileList1 = ref([]);

	// 删除图片
	const deletePic = (event) => {
		fileList1.value.splice(event.index, 1);
	};

	// 新增图片
	const afterRead = async (event) => {
		//console.log(fileList1.value)
		//console.log(event.file)
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		lists.map((item) => {
			fileList1.value.push({
				...item,
				status: 'success',
				message: '上传成功',
			});
		});

	};


	//验证码
	const {
		proxy
	} = getCurrentInstance();
	const tips = ref('');
	const seconds = ref(10);
	const uCodeRef = ref(null);

	const codeChange = (text) => {
		tips.value = text;
	};

	function checkPhone(mobile) {
		mobile = mobile + '';
		var tel = /^0\d{2,3}-?\d{7,8}$/;
		var phone = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;

		if (mobile.length === 11) { //手机号码
			if (phone.test(mobile)) {
				return true;
			}
		} else if (mobile.length === 12 && mobile.indexOf("-") !== -1) {
			if (tel.test(mobile)) {
				return true;
			}
		}
		return false;
	}

	function getCode() {

		proxy.$nextTick(async () => {
			if (agree.value == false) {
				uni.showToast({
					title: "请同意下方条款",
					mask: true,
					duration: 500
				})
			} else {
				if (checkPhone(registerForm.phone)) {
					console.log(proxy.$refs.uCode.canGetCode)
					if (proxy.$refs.uCode.canGetCode) {
						// 模拟向后端请求验证码
						uni.showLoading({
							title: '正在获取验证码',
						});
						setTimeout(() => {
							uni.hideLoading();
							// 这里此提示会被start()方法中的提示覆盖
							// uni.$u.toast('验证码已发送');
							// 通知验证码组件内部开始倒计时
							proxy.$refs.uCode.start();
						}, 2000);
					} else {
						uni.$u.toast('验证码已发送');
					}
				} else {
					uni.showToast({
						title: '手机号格式不对',
						duration: 1000,
						mask: true
					});
				}
			}
		})

	};



	const start = () => {
		uni.$u.toast('验证码已发送');
	};
</script>

<style lang="scss">
	body {
		background: url("/static/images/login.jpg") no-repeat center bottom fixed;
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;

		.register_content {
			position: relative;
			width: 90%;

			margin: 30rpx auto;
			padding: 20rpx;

			padding-top: 30rpx;
			box-shadow: 20rpx 20rpx 20rpx 20rpx rgba(0, 0, 0, 0.2);
			background-color: rgba(255, 255, 255, 0.7);
			font-size: 35rpx;
			border-radius: 20rpx;
		}
	}
</style>